package com.Aug.controller.user;

import com.Aug.constant.Constant;
import com.Aug.entity.Dept;
import com.Aug.entity.User;
import com.Aug.exception.UserIsExistException;
import com.Aug.service.UserService;
import com.Aug.util.DataUtil;
import com.Aug.util.IOUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.*;
import java.util.UUID;

@WebServlet("/user/register")
@MultipartConfig
public class RegisterServlet extends HttpServlet {

    UserService userService = new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
        //1、获取数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //获取文件部分
        Part profile = null;
        InputStream inputStream = null;
        try {
            profile = req.getPart("profile");
            inputStream = profile.getInputStream();
        }catch(IOException e)
        {
            e.printStackTrace();
        }

        if(profile == null || inputStream ==null){
            throw new RuntimeException("您必须上传头像");
        }

        //需要使用uuid进行处理
        String fileName = UUID.randomUUID() + "_" + profile.getSubmittedFileName();
        //给文件创建目录
        //1、日期的方案
        String format = DataUtil.getNowString();

        String path = Constant.BASE_PATH + format ;
        //若路径不存在，就创建
        File file = new File(path);
        if(!file.exists()) {
            file.mkdirs();
        }

//        //2、hash的方案
//        int pathInt = fileName.hashCode() % 10;
//
//        String path = Constant.BASE_PATH + pathInt ;
//        //若路径不存在，就创建
//        File file = new File(path);
//        if(!file.exists()) {
//            file.mkdirs();
//        }

        IOUtil.copy(inputStream,path + "/" + fileName);


        User user = new User(username,password,Constant.BASE_URL_PATH+format+"/"+ fileName);

        try {
            userService.register(user);
            resp.sendRedirect(req.getContextPath() + "/pages/success.jsp");
        }catch (UserIsExistException | IOException e){
            e.printStackTrace();
            try {
                resp.sendRedirect(req.getContextPath() + "/pages/error.jsp");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }


    }
}
